package com.cddx.logistics.service.impl;

import com.cddx.logistics.domain.dto.AnnualLedgerQueryDTO;
import com.cddx.logistics.domain.dto.LedgerQueryDTO;
import com.cddx.logistics.domain.dto.StockOperationCreateDTO;
import com.cddx.logistics.domain.dto.StockOperationQueryDTO;
import com.cddx.logistics.domain.pojo.StockOperation;
import com.cddx.logistics.domain.vo.*;
import com.cddx.logistics.mapper.StockOperationMapper;
import com.cddx.logistics.service.StockOperationService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StockOperationServiceImpl implements StockOperationService {
    @Resource
    private StockOperationMapper stockOperationMapper;

    @Override
        public PageInfo<AnnualLedgerVO> queryAnnualLedger(AnnualLedgerQueryDTO queryDTO) {
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getLimit());
        List<AnnualLedgerVO> list = stockOperationMapper.queryAnnualLedger(queryDTO);
        return new PageInfo<>(list);
    }

    /**
     * 查询出入库记录
     * @param queryDTO
     * @return
     */
    @Override
    public PageInfo<StockOperationVO> queryPage(StockOperationQueryDTO queryDTO) {
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getLimit());
        List<StockOperationVO> list = stockOperationMapper.queryPage(queryDTO);
        return new PageInfo<>(list);
    }

    /**
     * 根据id查询出入库记录
     * @param stockOperationId
     * @return
     */
    @Override
    public StockOperationVO getById(Long stockOperationId) {
        return stockOperationMapper.getById(stockOperationId);
    }

    /**
     * 创建出入库记录
     * @param createDTO
     * @return
     */
    @Override
    public boolean create(StockOperationCreateDTO createDTO) {
        StockOperation stockOperation = new StockOperation();
        stockOperation.setPlanNormalId(createDTO.getPlanNormalId());
        stockOperation.setOperationType(createDTO.getOperationType());
        stockOperation.setOperationTime(createDTO.getOperationTime());
        stockOperation.setRemark(createDTO.getRemark());

        return stockOperationMapper.insert(stockOperation) > 0;
    }

    /**
     * 修改出入库记录
     * @param stockOperation
     * @return
     */
    @Override
    public boolean update(StockOperation stockOperation) {
        return stockOperationMapper.update(stockOperation) > 0;
    }

    /**
     * 删除出入库记录
     * @param stockOperationId
     * @return
     */
    @Override
    public boolean delete(Long stockOperationId) {
        return stockOperationMapper.delete(stockOperationId) > 0;
    }

    /**
     * 获取配变电统计信息
     * @return
     */
    @Override
    public PowerTransformerStatsVO getPowerTransformerStats() {
        PowerTransformerStatsVO vo = new PowerTransformerStatsVO();

        // 设置图表数据
        PowerTransformerStatsVO.ChartData chartData = new PowerTransformerStatsVO.ChartData();
        chartData.setCompletedCount(stockOperationMapper.countCompletedPowerTransformerProjects());
        chartData.setPendingCount(stockOperationMapper.countPendingPowerTransformerProjects());
        vo.setChartData(chartData);

        // 设置表格数据
        List<PowerTransformerStatsVO.TableData> tableData = stockOperationMapper.getPowerTransformerProjects();
        vo.setTableData(tableData);
        vo.setTotal(tableData.size());

        return vo;
    }

    /**
     * 获取计划完成度统计信息
     * @return
     */
    @Override
    public PlanCompletionStatsVO getPlanCompletionStats() {
        return stockOperationMapper.getPlanCompletionStats();
    }

    /**
     * 获取备品统计信息
     * @param queryDTO
     * @return
     */
    @Override
    public Map<String, Object> getSparePartsStats(StockOperationQueryDTO queryDTO) {
        Map<String, Object> result = new HashMap<>();

        // 设置计划类型为"备品"
        queryDTO.setPlanType("备品");

        // 获取备品类型的统计（包含数量信息）
        List<SparePartsStatsVO> statsList = stockOperationMapper.getSparePartsStatsByType(queryDTO);

        // 准备图表数据
        List<String> categories = new ArrayList<>();
        List<BigDecimal> inData = new ArrayList<>();
        List<BigDecimal> outData = new ArrayList<>();

        statsList.forEach(item -> {
            categories.add(item.getMaterialsDescription());
            inData.add(item.getInQuantity() != null ? item.getInQuantity() : BigDecimal.ZERO);
            outData.add(item.getOutQuantity() != null ? item.getOutQuantity() : BigDecimal.ZERO);
        });

        result.put("categories", categories);
        result.put("inData", inData);
        result.put("outData", outData);

        return result;
    }


    /**
     * 获取新产品统计信息
     * @return
     */
    @Override
    public NewProductStatsVO getNewProductStats() {
        NewProductStatsVO vo = new NewProductStatsVO();

        // 设置图表数据
        NewProductStatsVO.ChartData chartData = new NewProductStatsVO.ChartData();
        chartData.setCompletedCount(stockOperationMapper.countCompletedNewProductProjects());
        chartData.setPendingCount(stockOperationMapper.countPendingNewProductProjects());
        vo.setChartData(chartData);

        // 设置表格数据
        List<NewProductStatsVO.TableData> tableData = stockOperationMapper.getNewProductProjects();
        vo.setTableData(tableData);
        vo.setTotal(tableData.size());

        return vo;
    }

    /**
     * 获取电缆统计信息
     * @return
     */
    @Override
    public Map<String, Object> getCableStatistics() {
        CableStatsVO stats = stockOperationMapper.getCableStatistics();

        // 计算总和
        BigDecimal copperTotal = stats.getCopperIn().add(stats.getCopperOut());
        BigDecimal aluminumTotal = stats.getAluminumIn().add(stats.getAluminumOut());

        Map<String, Object> result = new HashMap<>();
        result.put("copperIn", stats.getCopperIn());
        result.put("copperOut", stats.getCopperOut());
        result.put("aluminumIn", stats.getAluminumIn());
        result.put("aluminumOut", stats.getAluminumOut());
        result.put("copperTotal", copperTotal);
        result.put("aluminumTotal", aluminumTotal);

        return result;
    }

    /**
     * 获取线路统计信息
     * @param queryDTO
     * @return
     */
    @Override
    public List<LineStatsVO> getLineStats(StockOperationQueryDTO queryDTO) {
        // 设置计划类型为"线路"
        queryDTO.setPlanType("线路");
        return stockOperationMapper.getLineStats(queryDTO);
    }

    /**
     * 获取临措统计信息
     * @param queryDTO
     * @return
     */
    @Override
    public Map<String, Object> getTemporaryMeasureStats(StockOperationQueryDTO queryDTO) {
        Map<String, Object> result = new HashMap<>();

        // 设置计划类型为"临措"
        queryDTO.setPlanType("临措");

        // 获取临措统计数据
        List<TemporaryMeasureStatsVO> statsList = stockOperationMapper.getTemporaryMeasureStats(queryDTO);

        // 准备图表数据
        List<String> names = new ArrayList<>();
        List<BigDecimal> inQuantities = new ArrayList<>();
        List<BigDecimal> outQuantities = new ArrayList<>();
        List<String> completionRates = new ArrayList<>();

        statsList.forEach(item -> {
            names.add(item.getName());
            inQuantities.add(item.getInQuantity() != null ? item.getInQuantity() : BigDecimal.ZERO);
            outQuantities.add(item.getOutQuantity() != null ? item.getOutQuantity() : BigDecimal.ZERO);

            // 计算完成率
            BigDecimal total = item.getOutQuantity() != null ? item.getOutQuantity() : BigDecimal.ZERO;
            BigDecimal completed = item.getInQuantity() != null ? item.getInQuantity() : BigDecimal.ZERO;
            String rate = "0%";
            if (total.compareTo(BigDecimal.ZERO) > 0) {
                rate = completed.divide(total, 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal(100))
                        .setScale(2, RoundingMode.HALF_UP) + "%";
            }
            completionRates.add(rate);
        });

        result.put("names", names);
        result.put("inQuantities", inQuantities);
        result.put("outQuantities", outQuantities);
        result.put("completionRates", completionRates);

        return result;
    }


    /**
     * 获取项目完成率统计信息
     * @return
     */
    @Override
    public ProjectCompletionRateVO getProjectCompletionRate() {
        ProjectCompletionRateVO vo = new ProjectCompletionRateVO();

        // 获取总项目数
        Integer totalCount = stockOperationMapper.countAllProjects();
        vo.setTotalCount(totalCount);

        // 获取已完成项目数
        Integer completedCount = stockOperationMapper.countCompletedProjects();
        vo.setCompletedCount(completedCount);

        // 计算完成率和未完成率
        if (totalCount > 0) {
            double completedRate = (double) completedCount / totalCount * 100;
            double uncompletedRate = 100 - completedRate;
            vo.setCompletedRate(completedRate);
            vo.setUncompletedRate(uncompletedRate);
        } else {
            vo.setCompletedRate(0.0);
            vo.setUncompletedRate(0.0);
        }

        return vo;
    }

    // 查询库存操作记录并转换为LedgerVO(出入库台账)
    @Override
    public PageInfo<LedgerVO> queryPageToLedger(LedgerQueryDTO queryDTO) {
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getLimit());
        List<LedgerVO> list = stockOperationMapper.queryPageToLedger(queryDTO);
        return new PageInfo<>(list);
    }

}